package com.jielin.handling.service.casegoods.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.github.pagehelper.PageInfo;
import com.jielin.handling.entity.unit.Organization;
import com.jielin.handling.entity.unit.OrganizationVo;
import com.jielin.handling.entity.vo.PoliceVo;
import com.jielin.handling.mapper.unit.UnitMapper;
import com.jielin.handling.service.accesspath.AccessPathService;
import com.jielin.handling.service.policeplatform.PolicePlatformService;
import com.jielin.handling.service.tsuspect.TSuspectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.entity.casegoods.CaseGoods;
import com.jielin.handling.entity.casegoods.CaseGoodsAuditResult;
import com.jielin.handling.entity.casegoods.CaseGoodsAuditResultVo;
import com.jielin.handling.entity.casegoods.CaseGoodsMoreVo;
import com.jielin.handling.entity.casegoods.CaseGoodsVo;
import com.jielin.handling.entity.casegoods.CaseGoodsVoLess;
import com.jielin.handling.entity.casegoods.CaseGoodsVoSpay;
import com.jielin.handling.entity.dict.Dict;
import com.jielin.handling.entity.police.PoliceMan;
import com.jielin.handling.entity.vo.CaseVo;
import com.jielin.handling.entity.vo.GoodsAmountVo;
import com.jielin.handling.mapper.casegoods.CaseGoodsAuditResultMapper;
import com.jielin.handling.mapper.dict.DictMapper;
import com.jielin.handling.page.DataGrid;
import com.jielin.handling.service.casegoods.CaseGoodsAuditResultService;
import com.jielin.handling.util.DateUtil;
import com.jielin.handling.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CaseGoodsAuditResultServiceImpl implements CaseGoodsAuditResultService {
    @Autowired
    CaseGoodsAuditResultMapper caseGoodsAuditResultMapper;
    @Autowired
    DictMapper dictMapper;
    @Autowired
    PolicePlatformService platformService;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    AccessPathService accessPathService;
    @Autowired
    TSuspectService tSuspectService;

    @Override
    public DataGrid findCaseGoodsAuditResult(CaseGoodsAuditResult caseGoodsAuditResult) {
        log.info("查询物品审核列表条件：" + JSONObject.toJSONString(caseGoodsAuditResult));

        //查询角色是否管理员true为管理员false警员
        boolean power = accessPathService.findPowerIsBig(caseGoodsAuditResult.getPoliceId());

        PageHelper.startPage(
                caseGoodsAuditResult.getPageNum() == null ? 1 : caseGoodsAuditResult.getPageNum(),
                caseGoodsAuditResult.getPageSize() == null ? 10 : caseGoodsAuditResult.getPageSize());
        List<CaseGoodsAuditResultVo> list =null;

        //如果为管理员查询所有
        if(power){
            list = caseGoodsAuditResultMapper.findCaseGoodsAuditResult(caseGoodsAuditResult);
        }else{
            //只能查询自己的
            PoliceVo policeVo = tSuspectService.selectPolice(caseGoodsAuditResult.getPoliceId());
            caseGoodsAuditResult.setApplyPolice(policeVo.getPoliceCode());
            list = caseGoodsAuditResultMapper.findCaseGoodsAuditResult(caseGoodsAuditResult);
        }



        PageInfo<CaseGoodsAuditResultVo> startPage = new PageInfo<>(list);
                DataGrid dg = new DataGrid();
        dg.setRows(startPage.getList());
        dg.setTotal(startPage.getTotal());
        return dg;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int updateCaseGoodsAuditResult(CaseGoodsAuditResult caseGoodsAuditResult) {
        if (StringUtil.isEmptyObJ(caseGoodsAuditResult, caseGoodsAuditResult.getId(), caseGoodsAuditResult.getFindingsOfAudit())) {
            return -1;
        }
        CaseGoodsAuditResult logAuditResult = caseGoodsAuditResultMapper
                .selectByPrimaryKey(caseGoodsAuditResult.getId());
        int flag = -1;
        if (logAuditResult != null) {
            logAuditResult.setId(StringUtil.generatorUUID());
            try {
                //当前时间
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");//注意月份是MM
                String colonFormatDate = DateUtil.getColonFormatDate();
                Date date = simpleDateFormat.parse(colonFormatDate);
                //状态为审核通过才添加出库时间
                //(1101.初始入库,1102,借出,1103.归还入库1104.送检,1105移交,1106.销毁,1107拍卖,1108.上缴国库)
                if("1".equals(caseGoodsAuditResult.getFindingsOfAudit())){
                    switch(logAuditResult.getGoodsWarehousing()){
                        case "1102" :
                        case "1104" :
                        case "1105" :
                        case "1106" :
                        case "1107" :
                        case "1108" :
                            caseGoodsAuditResult.setGoodsTransferDate(date);
                            caseGoodsAuditResultMapper.updateByPrimaryKey(caseGoodsAuditResult);
                            break;
                        //入库时间
                        case "1103" :
                            // 记录修改物品审核状态的日志
                            logAuditResult.setIsNew("1");//最新状态
                            logAuditResult.setGoodsWarehousingDate(date);
                            logAuditResult.setGoodsTransferDate(null);
                            logAuditResult.setFindingsOfAudit(caseGoodsAuditResult.getFindingsOfAudit());
                            caseGoodsAuditResultMapper.insert(logAuditResult);
                            //设置为历史状态
                            caseGoodsAuditResult.setIsNew("0");
                            caseGoodsAuditResultMapper.updateByPrimaryKey(caseGoodsAuditResult);
                            break;
                        case "1101" :
                            caseGoodsAuditResultMapper.updateByPrimaryKey(caseGoodsAuditResult);
                            break;
                    }
                }else{
                    caseGoodsAuditResultMapper.updateByPrimaryKey(caseGoodsAuditResult);
                }


                flag = 1;
            } catch (Exception e) {
                log.info("updateCaseGoodsAuditResult 事务回滚:{}", e);
                // 抛出异常让其回滚
                throw new RuntimeException("事务回滚");
            }
        }
        return flag;
    }

    @Override
    public CaseGoodsVo findCaseGoodsById(String id) {
        if (StringUtil.isEmpty(id)) {
            return null;
        }
        return caseGoodsAuditResultMapper.findCaseGoodsById(id);
    }

    @Override
    public DataGrid findCaseGoodsByCaseCode(CaseGoodsAuditResult caseGoodsAuditResult) {
        log.info("根据案件编号查询物品详细信息列表条件：" + JSONObject.toJSONString(caseGoodsAuditResult));
        if (StringUtil.isEmptyObJ(caseGoodsAuditResult, caseGoodsAuditResult.getCaseCode())) {
            return null;
        }
        PageHelper.startPage(
                caseGoodsAuditResult.getPageNum() == null ? 1 : caseGoodsAuditResult.getPageNum(),
                caseGoodsAuditResult.getPageSize() == null ? 10 : caseGoodsAuditResult.getPageSize());
        List<CaseGoodsVoLess> list = caseGoodsAuditResultMapper.findCaseGoodsByCaseCode(caseGoodsAuditResult.getCaseCode(),
                caseGoodsAuditResult.getPoliceCode());
        PageInfo<CaseGoodsVoLess> startPage = new PageInfo<>(list);
                DataGrid dg = new DataGrid();
        dg.setRows(startPage.getList());
        dg.setTotal(startPage.getTotal());
        return dg;
    }

    @Override
    public DataGrid findCaseGoodsLogs(CaseGoodsAuditResult caseGoodsAuditResult) {
        boolean power = accessPathService.findPowerIsBig(caseGoodsAuditResult.getPoliceId());
        DataGrid dg = new DataGrid();
        PageHelper.startPage(
                caseGoodsAuditResult.getPageNum() == null ? 1 : caseGoodsAuditResult.getPageNum(),
                caseGoodsAuditResult.getPageSize() == null ? 10 : caseGoodsAuditResult.getPageSize());
        if(power){
            List<CaseGoodsAuditResultVo> list = caseGoodsAuditResultMapper.findCaseGoodsLogs(caseGoodsAuditResult);
            PageInfo<CaseGoodsAuditResultVo> startPage = new PageInfo<>(list);
            dg.setRows(startPage.getList());
            dg.setTotal(startPage.getTotal());
        }else{
            //只能查询自己的
            PoliceVo policeVo = tSuspectService.selectPolice(caseGoodsAuditResult.getPoliceId());
            caseGoodsAuditResult.setApplyPolice(policeVo.getPoliceCode());
            List<CaseGoodsAuditResultVo> list = caseGoodsAuditResultMapper.findCaseGoodsLogs(caseGoodsAuditResult);
            PageInfo<CaseGoodsAuditResultVo> startPage = new PageInfo<>(list);
            dg.setRows(startPage.getList());
            dg.setTotal(startPage.getTotal());
        }
        return dg;
    }

    @Override
    public CaseGoodsMoreVo findCaseGoodsLogsById(CaseGoodsAuditResult caseGoodsAuditResult) {
        log.info("查询涉案物品的详细操作日志：" + JSONObject.toJSONString(caseGoodsAuditResult));
        if (StringUtil.isEmptyObJ(caseGoodsAuditResult, caseGoodsAuditResult.getId())) {
            return null;
        }
        List<List<Object>> CaseGoodsList = new ArrayList<>();
        List<Object> list = new ArrayList<>();
        // 查询涉案财物基本信息
        list.add(caseGoodsAuditResultMapper.findCaseInfoGoodsById(caseGoodsAuditResult.getId()));
        // 涉案物品信息
        list.add(caseGoodsAuditResultMapper.findCaseGoodsLogsById(caseGoodsAuditResult));
        CaseGoodsList.add(list);
        // 案件信息
        return CaseGoodsMoreVo.builder()
                .caseGoodsBaseVo(caseGoodsAuditResultMapper.findCaseInfoByCaseGoodsId(caseGoodsAuditResult.getId()))
                .caseGoods(CaseGoodsList).build();
    }

    @Override
    public CaseGoodsMoreVo findCaseGoodsLogsByCaseCode(CaseGoodsAuditResult caseGoodsAuditResult) {
        log.info("查询该案件下的涉案物品的详细操作日志：" + JSONObject.toJSONString(caseGoodsAuditResult));
        if (StringUtil.isEmptyObJ(caseGoodsAuditResult, caseGoodsAuditResult.getCaseCode())) {
            return null;
        }
        List<List<Object>> CaseGoodsList = new ArrayList<>();
        // 查出该案件下的涉案物品id
        List<String> caseGoodsIds = caseGoodsAuditResultMapper.findCaseGoodsIdByCaseCode(caseGoodsAuditResult);
        List<Object> list = null;
        for (String caseGoodsId : caseGoodsIds) {
            list = new ArrayList<>();
            // 查询涉案财物基本信息
            list.add(caseGoodsAuditResultMapper.findCaseInfoGoodsById(caseGoodsId));
            // 涉案物品信息
            list.add(caseGoodsAuditResultMapper
                    .findCaseGoodsLogsById(CaseGoodsAuditResult.builder().id(caseGoodsId).build()));
            CaseGoodsList.add(list);
        }
        // 案件信息
        return CaseGoodsMoreVo.builder()
                .caseGoodsBaseVo(caseGoodsAuditResultMapper.findCaseInfoByCaseCode(caseGoodsAuditResult.getCaseCode()))
                .caseGoods(CaseGoodsList).build();
    }

    @Override
    public CaseGoodsVoSpay findCaseInfoGoodsById(String id) {
        if (StringUtil.isEmpty(id)) {
            return null;
        }
        return caseGoodsAuditResultMapper.findCaseInfoGoodsById(id);
    }

    @Override
    public LinkedHashMap<String, Integer> findCaseGoodsAuditResultPassingRate(
            CaseGoodsAuditResult caseGoodsAuditResult) {
        if (caseGoodsAuditResult == null || StringUtil.isEmpty(caseGoodsAuditResult.getOrgIds())
                || caseGoodsAuditResult.getSwitchDate() == null) {
            return null;
        }
        coverParam(caseGoodsAuditResult);
        switch (caseGoodsAuditResult.getSwitchDate()) {
            case 0:// 0=年，查询最近六年
                caseGoodsAuditResult.setSwitchPart(generateOrderArray(DateUtil.getYear() - 5, 6));
                break;
            case 1:// 1=月，查询最近12个月
                caseGoodsAuditResult.setSwitchPart(generateOrderArray(1, 12));
                break;
            case 2:// 2=日，查询最近30日
                // 获取当月有多少天
                caseGoodsAuditResult.setSwitchPart(generateOrderArray(1, DateUtil.getDaysOfMonth(new Date())));
                break;
            default:
                break;
        }
        if (caseGoodsAuditResult.getSwitchPart() != null) {
            return caseGoodsAuditResultMapper.findCaseGoodsAuditResultPassingRate(caseGoodsAuditResult);
        }
        return null;
    }

    /**
     * @param begin 从几开始
     * @param size  数组长度
     * @return 从begin开始加1填入数组
     */
    private int[] generateOrderArray(int begin, int size) {
        int[] flag = new int[size];
        for (int i = 0; i < flag.length; i++) {
            flag[i] = begin++;
        }
        return flag;
    }

    /**
     * 设置单位id数组
     *
     * @param caseGoodsAuditResult
     * @return
     */
    private void coverParam(CaseGoodsAuditResult caseGoodsAuditResult) {
        caseGoodsAuditResult.setOrgIdArray(caseGoodsAuditResult.getOrgIds().split(","));
    }

    @Override
    public List<CaseGoods> selectBeOverdue(String orgIds) {
        if (StringUtil.isEmpty(orgIds)) {
            return null;
        }
        return caseGoodsAuditResultMapper.selectBeOverdue(orgIds.split(","));
    }

    @Override
    public List<GoodsAmountVo> selectLocation(GoodsAmountVo vo) {
        if (vo == null || StringUtil.isEmpty(vo.getOrgIds())) {
            return null;
        }
        vo.setArray(vo.getOrgIds().split(","));
        return caseGoodsAuditResultMapper.selectLocation(vo);
    }

    @Override
    public Map<String, Object> findCaseGoodsTypeRate(CaseGoodsAuditResult caseGoodsAuditResult) {
        if (StringUtil.isEmptyObJ(caseGoodsAuditResult, caseGoodsAuditResult.getOrgIds())) {
            return null;
        }
        coverParam(caseGoodsAuditResult);
        // 获取涉案物品类型
        List<Dict> list = dictMapper.getListByParentCode("10");
        HashMap<String, Object> result = caseGoodsAuditResultMapper.findCaseGoodsTypeRate(list, caseGoodsAuditResult);
        HashMap<String, Object> returnList = new HashMap<>();
        List<Object> key = new ArrayList<>(list.size());
        List<Object> value = new ArrayList<>(list.size());
        if (result != null) {
//			result.forEach((k, v) -> {
//				key.add(k);
//				value.add(v);
//			});
            key.add(result.keySet());
            value.add(result.values());
        } else {// 可以去掉这里的if,else（sql不会返回null因为加了IFNULL()）
            list.stream().map(Dict::getNodeName).forEach(item -> {
                key.add(item);
                value.add(0);
            });
        }
        returnList.put("title", key);
        returnList.put("value", value);
        return returnList;
    }

    @Override
    public List<PoliceMan> selectDropList(String []unitcode,JSONObject json) {

        //查询角色是否管理员true为管理员false警员
        boolean power = accessPathService.findPowerIsBig(json.getString("policeId"));

        //如果为管理员查询所有
        if(power){
            return  caseGoodsAuditResultMapper.selectDropList(unitcode,"");
        }else{
            //只能查询自己的
            PoliceVo policeVo = tSuspectService.selectPolice(json.getString("policeId"));

            String policeCode =policeVo.getPoliceCode();

            return   caseGoodsAuditResultMapper.selectDropList(unitcode,policeCode);
        }
    }

    @Override
    public List<CaseVo> selectCodeAndName(String unitcode) {
        return caseGoodsAuditResultMapper.selectCodeAndName(unitcode);
    }

    @Override
    public Map<String, List<Object>> findCaseGoodsStatusRate(CaseGoodsAuditResult caseGoodsAuditResult) {
        if (StringUtil.isEmptyObJ(caseGoodsAuditResult, caseGoodsAuditResult.getOrgIds())) {
            return null;
        }
        coverParam(caseGoodsAuditResult);
        // 获取涉案财物入库借阅状态
        List<Dict> list = dictMapper.getListByParentCode("11");
        HashMap<String, BigDecimal> result = caseGoodsAuditResultMapper.findCaseGoodsStatusRate(list,
                caseGoodsAuditResult);
        HashMap<String, List<Object>> returnList = new HashMap<>();
        List<Object> key = new ArrayList<>();
        List<Object> value = new ArrayList<>();
        // 入库数量
        BigDecimal storageCount = BigDecimal.ZERO;
        // 归还入库数量
        BigDecimal returnCount = BigDecimal.ZERO;
        // 出库数量
        BigDecimal outCount = BigDecimal.ZERO;
        /*
         * 需要多遍历一遍 map for (Entry<String, BigDecimal> item : result.entrySet()) { switch
         * (item.getKey()) { case "初始入库": storageCount =
         * storageCount.add(item.getValue()); break; case "归还入库": returnCount =
         * returnCount.add(item.getValue()); break; case "销毁": case "上缴国库": case "拍卖":
         * case "移交": case "借阅": case "送检": outCount = outCount.add(item.getValue());
         * break; default: break; } }
         */
        storageCount = storageCount.add(result.get("初始入库"));
        returnCount = returnCount.add(result.get("归还入库"));
        outCount = outCount.add(result.get("销毁"));
        outCount = outCount.add(result.get("上缴国库"));
        outCount = outCount.add(result.get("拍卖"));
        outCount = outCount.add(result.get("移交"));
        outCount = outCount.add(result.get("借出"));
        outCount = outCount.add(result.get("送检"));
        key.add("入库");
        key.add("归还入库");
        key.add("出库");
        value.add(storageCount);
        value.add(returnCount);
        value.add(outCount);
        returnList.put("title", key);
        returnList.put("value", value);
        return returnList;
    }

    @Override
    public List<OrganizationVo> findUnitInfoByUnitCodeS(String unitCodes) {
        return UnitInfoEX(unitCodes, "-1", new ArrayList<>());
    }

    @Override
    public List<Map<String, Object>> selectLateRemind(String[] array) {
        return caseGoodsAuditResultMapper.selectLateRemind(array);
    }

    // 递归查询本单位及其所有子单位信息
    public List<OrganizationVo> UnitInfoEX(String unitCode, String parentId, List<OrganizationVo> childListEX) {

        Organization parentO = unitMapper.findUnitInfoByCode(unitCode);// 查询本单位信息
        if (parentO == null) {
            return new ArrayList<>();
        }

        OrganizationVo thisParent = new OrganizationVo();
        thisParent.setOrgId(parentO.getId());
        thisParent.setHandleUnitCode(parentO.getHandleUnitCode());
        thisParent.setOrgName(parentO.getOrganizationName());
        thisParent.setSite(StringUtil.isEmpty(parentO.getSite()) ? "" : parentO.getSite());
        thisParent.setSuperId(parentId);
        thisParent.setSelected(true);
        childListEX.add(thisParent);

        List<Organization> thisChildO = unitMapper.findChildUnitInfoById(parentO.getId());// 查询当前单位子单位信息

        if (StringUtil.isEmpty(unitCode)) {
            return new ArrayList<>();
        } else if (thisChildO.size() > 0) {
            for (Organization childO : thisChildO) {
                UnitInfoEX(childO.getHandleUnitCode(), parentO.getId(), childListEX);
            }
        }
        return childListEX;
    }
}
